package shuashuami.hb.com.avtivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scrat.app.selectorlibrary.ImageSelector;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import shuashuami.hb.com.adapter.ComplaintAdatper;
import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.glid.GlidUtil;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.http.HttpBMethods;
import shuashuami.hb.com.http.HttpCMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.http.LoginHttp;
import shuashuami.hb.com.http.SubmitCTaskHttp;
import shuashuami.hb.com.share.ShareCUserInfo;

public class CUntreatedTaskInfoActivity extends AbActivity {
    private GridView gridView;
    private ComplaintAdatper complaintAdatper;
    private List<String> imgs;
    private static final int REQUEST_CODE_SELECT_IMG = 1;
    private static final int MAX_SELECT_COUNT = 9;


    private String id;

    private TextView tvEndTime;
    private TextView tvTitle, tvTuangoujia, tvZongyongjin, tvPingtai, tvDaili, tvShangji, tvWo;
    private ImageView imgTaskImage;
    private EditText edtShouhuoXingming, edtShouji, edtDingdanhao;

    private Button btnSubmit;

    private GlidUtil glidUtil;

    private LinearLayout llBack;

    @Override
    protected void initUI() {
        setAbContentView(R.layout.activity_cuntreated_task_info);
        gridView = (GridView) findViewById(R.id.gv_complaint);
        tvEndTime = (TextView) findViewById(R.id.tv_cuntreated_task_info_shengyu_shijain);
        tvTitle = (TextView) findViewById(R.id.tv_cuntreated_task_info_message);
        tvTuangoujia = (TextView) findViewById(R.id.tv_cuntreated_task_info_tuangoujia);
        tvZongyongjin = (TextView) findViewById(R.id.tv_cuntreated_task_info_zong_yongjin);
        tvPingtai = (TextView) findViewById(R.id.tv_cuntreated_task_info_pingtai);
        tvDaili = (TextView) findViewById(R.id.tv_cuntreated_task_info_daili);
        tvShangji = (TextView) findViewById(R.id.tv_cuntreated_task_info_shangji);
        tvWo = (TextView) findViewById(R.id.tv_cuntreated_task_info_wo);
        imgTaskImage = (ImageView) findViewById(R.id.img_cuntreated_task_info_task_image);
        edtShouhuoXingming = (EditText) findViewById(R.id.edt_cuntreated_task_info_shouhuoren_xingming);
        edtShouji = (EditText) findViewById(R.id.edt_cuntreated_task_info_shouji_haoma);
        edtDingdanhao = (EditText) findViewById(R.id.edt_cuntreated_task_info_tianxie_dingdan_bianhao);

        btnSubmit = (Button) findViewById(R.id.btn_cuntreated_task_info_submit);
        llBack = (LinearLayout) findViewById(R.id.ll_back);
    }

    @Override
    protected void initData() {
        setTitleBar("提交订单");
        glidUtil = new GlidUtil(this)
        ;
        setLeftView();
        initAdapter();
        Bundle bundle = this.getIntent().getExtras();/*获取Bundle中的数据，注意类型和key*/
        id = bundle.getString("id");
        //   edtDingdanhao.setText(bundle.getString("num"));
        getMessage();
    }

    private void initAdapter() {
        imgs = new ArrayList<>();
        imgs.add(R.mipmap.ssm_icon_127 + "");
        complaintAdatper = new ComplaintAdatper(this, imgs);
        gridView.setAdapter(complaintAdatper);

    }

    @Override
    protected void initListener() {
        llBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        setLeftViewListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imgs.size() - 1) {
                    if (imgs.size() <= 9) {
                        ImageSelector.show(CUntreatedTaskInfoActivity.this, REQUEST_CODE_SELECT_IMG, MAX_SELECT_COUNT);
                    }
                }
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
    }

    private void showContent(Intent data) {
        List<String> paths = ImageSelector.getImagePaths(data);
        if (!paths.isEmpty()) {
            for (int i = 0; i < paths.size(); i++) {
                imgs.add(0, paths.get(i));
            }
            complaintAdatper.notifyDataSetChanged();
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_SELECT_IMG) {
            showContent(data);
            return;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getMessage() {
        progressDialog = ProgressDialog.show(this, "加载中...", "请稍后...", true, false);
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(this);
        HttpCMethods.getHallInfo(listener, shareCUserInfo.getId(), id);
    }

    private double commission;

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    try {
                        progressDialog.dismiss();
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(CUntreatedTaskInfoActivity.this);
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject.getInt("status") == 200) {
                            JSONObject temp = jsonObject.getJSONObject("content");
                            glidUtil.uploadRound(temp.getString("goods_image"), 10, imgTaskImage);
                            toTime(temp.getLong("expiretime") - System.currentTimeMillis() / 1000);
                            ss = temp.getLong("expiretime") - System.currentTimeMillis() / 1000;
                            tvTitle.setText(temp.getString("goods_title"));
                            tvTuangoujia.setText("商品价格：" + temp.getString("price") + "元");
                            tvZongyongjin.setText("¥" + temp.getString("commission"));
                            commission = temp.getDouble("commission");
                            baseConfig();
                        } else {
                            ToastUtil.showShort(CUntreatedTaskInfoActivity.this, jsonObject.getString("message"));
                        }

                    } catch (JSONException e) {
                        ToastUtil.showShort(CUntreatedTaskInfoActivity.this, "数据解析错误");
                    }
                    break;

                case 2:
                    JSONObject jsonObject2 = null;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    try {
                        jsonObject2 = new JSONObject(msg.obj.toString());
                        if (jsonObject2.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(CUntreatedTaskInfoActivity.this);
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject2.getInt("status") == 200) {
                            JSONObject temp = jsonObject2.getJSONObject("content");
                            double commission_platform = temp.getDouble("commission_platform");
                            tvPingtai.setText("¥" + decimalFormat.format(commission_platform));
                            Message message = handler.obtainMessage(3);
                            handler.sendMessageDelayed(message, 1000);      // send message
                            ShareCUserInfo shareCUserInfo = new ShareCUserInfo(CUntreatedTaskInfoActivity.this);
                            if (shareCUserInfo.getParent_id().equals("0")) {
                                tvDaili.setText("¥" + decimalFormat.format(temp.getDouble("commission_agent")));
                                tvShangji.setText("¥0");
                            } else {
                                double commission_parent = temp.getDouble("commission_parent");
                                tvDaili.setText("¥" + decimalFormat.format(commission_parent - commission_parent * temp.getDouble("commission_parent")));
                                tvShangji.setText("¥" + decimalFormat.format(commission_parent * temp.getDouble("commission_parent")));
                            }
                            tvWo.setText("¥" + decimalFormat.format(commission - commission_platform - temp.getDouble("commission_agent")));

                        } else {
                            ToastUtil.showShort(CUntreatedTaskInfoActivity.this, jsonObject2.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case 3:
                    ss -= 1;
                    toTime(ss);
                    if (ss > 0) {
                        Message message = handler.obtainMessage(3);
                        handler.sendMessageDelayed(message, 1000);      // send message
                    } else {
                        tvEndTime.setVisibility(View.GONE);
                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };
    private long h, m, s;
    private long ss;

    private void toTime(long ss) {
        h = ss / 3600;
        m = (ss % 3600) / 60;
        s = ss - h * 3600 - m * 60;
        String strh = "";
        if (h < 10) {
            strh = "0" + h;
        } else {
            strh = h + "";
        }
        String strm = "";
        if (m < 10) {
            strm = "0" + m;
        } else {
            strm = m + "";
        }
        String strs = "";
        if (s < 10) {
            strs = "0" + s;
        } else {
            strs = s + "";
        }
        tvEndTime.setText(strh + ":" + strm + ":" + strs);
    }

    public void baseConfig() {
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(2);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        HttpBMethods.baseConfig(listener);
    }

    private String toHH(Long ms) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//初始化Formatter的转换格式。

        String hms = formatter.format(ms);
        return hms;
    }

    private ProgressDialog progressDialog;

    //提交订单
    private void submit() {
        SubmitCTaskHttp submitCTaskHttp = new SubmitCTaskHttp(this);
        submitCTaskHttp.uploadImg(id, edtShouhuoXingming.getText().toString(), edtShouji.getText().toString(),
                edtDingdanhao.getText().toString(), imgs);
    }
}
